<template>
  <div class="app-container">
    <div style="background-color: #fff">
      <div class="container-module" style="padding: 10px 0 0 10px">
        <el-form :inline="true" class="search-form" size="small">
          <el-row style="display: flex">
            <div style="flex: 1">
              <el-form-item class="search-form-item" label="关键字" style="margin: 5px 0">
                <el-input clearable placeholder="请输入关键字" v-model="searchForm.params.keywords" class="input-with-select">
                </el-input>
              </el-form-item>
              <el-form-item class="search-form-item" label="供应商" style="margin: 5px 0">
                <el-select style="width: 100%" clearable v-model="searchForm.params.supplier_id" filterable
                  placeholder="请输入供货商名称搜索">
                  <el-option v-for="item in options" :key="item.id" :label="item.supplier_name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="search-form-item" label="商户" style="margin: 5px 0">
                <el-select style="width: 100%" clearable v-model="searchForm.params.mer_id" filterable
                  placeholder="请输入商户名称搜索">
                  <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div style="padding: 5px 0">
              <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="getcatelist">查询</el-button>
                <el-button size="small" type="primary" icon="el-icon-refresh" @click="resetting">重置</el-button>
                <el-button v-if="!searchDisplay" type="warning" icon="el-icon-caret-bottom"
                  @click="searchDisplay = true">展开</el-button>
                <el-button v-else type="warning" icon="el-icon-caret-top" @click="searchDisplay = false">收起</el-button>
              </el-form-item>
            </div>
          </el-row>
          <el-row v-if="searchDisplay" style="display: flex">
            <el-form-item class="search-form-item" label="分类" style="margin: 5px 0">
              <el-cascader clearable v-model="searchForm.params.cate_ids" :options="typeData" :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  value: 'id',
                  label: 'category_name',
                }" @change="handleChange" placeholder="请选择类目ID"></el-cascader>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <el-divider></el-divider>
      <div style="padding: 0 20px 20px">
        <div class="marginBottom">
          <el-row :gutter="20">
            <el-col :span="21">
              <div class="left-panel">
                <el-button icon="el-icon-circle-plus-outline" type="primary" size="small"
                  @click="goodsadd()">选配商品</el-button>
                <el-button type="danger" icon="el-icon-delete" size="small" @click="batch_deletion()">批量删除</el-button>
              </div>
            </el-col>
            <el-col :span="3" style="text-align: right;">
              <el-tooltip class="item" effect="dark" content="保存当前页面的商品配置" placement="top-start">
              <el-button type="warning" size="small" :loading="settsub" @click="submitForms()">保存当前配置</el-button>
              </el-tooltip>
            </el-col>
          </el-row>
        </div>
        <el-row :gutter="20">
          <el-form ref="allocationform" :model="formData" :rules="formRules" inline>
            <el-col class="new_table_card" style="overflow-y: auto;">
              <el-table ref="multipleTable" v-loading="loading" :data="formData.tableData" :header-cell-style="{
                'background-color': '#e5eeff',
                color: '#515a6e',
                height:'50px',
              }" @selection-change="handleSelectionChange" style="width: 100%;" height="100%">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="goods_id" label="商品ID" align="center" width="60">
                </el-table-column>
                <el-table-column prop="name" label="商品名称" align="center">
                  <template slot-scope="scope">
                    <el-tooltip placement="top-start" :content="scope.row.goods_name + ''">
                      <div class="one_line_hidden">
                        {{ scope.row.goods_name ? scope.row.goods_name : "-" }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="category_name1" label="商品分类" align="center" width="90">
                  <template slot-scope="scope">
                    <el-tooltip placement="top-start"
                      :content="scope.row.category_name1 ? scope.row.category_name1 + '' : ''">
                      <div class="one_line_hidden">
                        {{ scope.row.category_name1 ? scope.row.category_name1 : "-" }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="main_image" label="商品图片" align="center" width="90">
                  <template slot-scope="scope">
                    <div style="width: 36px; height: 36px; margin: 0 auto">
                      <el-image v-if="scope.row.main_image" :src="scope.row.main_image"
                        :preview-src-list="[scope.row.main_image]" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="supplier" label="所属店铺" align="center" width="90">
                  <template slot-scope="scope">
                    <el-tooltip placement="top-start" :content="scope.row.mer_name ? scope.row.mer_name + '' : ''">
                      <div class="one_line_hidden">
                        {{ scope.row.mer_name ? scope.row.mer_name : "-" }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="retail_price" label="商品价格" align="center" width="90">
                  <template slot-scope="scope">
                    <el-tooltip placement="top-start"
                      :content="scope.row.retail_price ? scope.row.retail_price + '' : ''">
                      <div class="one_line_hidden">
                        {{ scope.row.retail_price ? scope.row.retail_price : "-" }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="奖励类型" align="center" width="170">
                  <template slot-scope="scope">
                    <el-col style="margin-top:10px">
                      <el-form-item :prop="`tableData.${scope.$index}.level`" :rules="formRules.nonempty">
                        <el-select v-model="scope.row.level" placeholder="请选择">
                          <el-option v-for="item in type_rules" :key="item.value" :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column label="发放时间" align="center" width="160">
                  <template slot-scope="scope">
                    <el-col style="margin-top:10px">
                      <el-form-item :prop="`tableData.${scope.$index}.node_day`" :rules="formRules.newFieldName">
                        <el-input controls-position="right" v-model="scope.row.node_day" placeholder="T+?">
                          <template slot="prepend">T+</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column label="时间节点" align="center" width="150">
                  <template slot-scope="scope">
                    <el-col style="margin-top:10px">
                      <el-form-item :prop="`tableData.${scope.$index}.node_type`" :rules="formRules.nonemptys">
                        <el-select v-model="scope.row.node_type" placeholder="请选择">
                          <el-option v-for="item in mouchoptions" :key="item.value" :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column label="奖励规则" align="center" width="190">
                  <template slot-scope="scope">
                    <el-col style="margin-top:10px">
                      <el-form-item :prop="`tableData.${scope.$index}.award_type`" :rules="formRules.nonempty">
                        <el-select v-model="scope.row.award_type" placeholder="请选择">
                          <el-option v-for="item in reward_rules" :key="item.value" :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column label="规则配置" align="center" width="220">
                  <template slot-scope="scope">
                    <span>有{{scope.row.goods_rule ? scope.row.goods_rule.length : '0'}}条规则</span>
                    <span style="color:#0076f6;margin-left:16px;">
                      <el-button @click="settallocation(scope.row.goods_rule,scope.row.id)" type="text">配置</el-button>
                      </span>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" prop="address" label="操作" align="center" width="160px">
                  <template slot-scope="scope">
                    <el-button type="success" size="mini" style="margin-right: 10px;width: 50px;" @click="singlesubmit(scope.row,scope.row.id)">
                      保存
                    </el-button>
                    <el-popconfirm title="确定移除此条商品吗？" @confirm="goodsremoves(scope.row.id)">
                      <el-button type="danger" size="mini" style="width: 50px;"
                        slot="reference">
                        移除
                      </el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table></el-col>
          </el-form>
          <el-col>
            <pagination v-show="total > 0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.count"
              @pagination="getcatelist" />
          </el-col>
        </el-row>
      </div>
    </div>
    <oneallocation ref="refoneallocation" />
    <productConfig v-if="ifShowProductConfig"></productConfig>
  </div>
</template>
<script>
  import addproduct from "./components/addproduct";
  import oneallocation from "./components/oneallocation";
  import productConfig from "./components/productConfig";
  import {
    goodslist,
    goodsremove,
    goodssave
  } from "@/api/plugins";
  import {
    getMerchantList,
  } from '@/api/merchant/index'
  import {
    supplierLists,
    getCateLis
  } from "@/api/supplier/index";
  export default {
    components: {
      productConfig,
      oneallocation
    },
    data() {
      return {
        settsub: false,
        ifShowProductConfig: false,
        type_rules: [{
            value: 1,
            label: '仅直推'
          },
          {
            value: 2,
            label: '直推+间推'
          }
        ],
        reward_rules: [{
            value: 1,
            label: '按支付金额'
          },
          {
            value: 2,
            label: '按商品利润金额'
          }
        ],
        mouchoptions: [{
            value: 1,
            label: '支付成功'
          }, {
            value: 2,
            label: '确认收货'
          }, {
            value: 3,
            label: '评价后'
          },
          {
            value: 4,
            label: '过售后期'
          }
        ],
        //表单校验
        formRules: {
          moneynumber: [{
            required: false,
            validator: (rule, value, callback) => {
              let req = /^\d+(\.\d{1,2})?%?$/;
              let regex = /%/;
              if (regex.test(value)) {
                let jsx = /^\d+(\.\d{1,2})?%?$/;
                // let jsx = /^(100|\d{1,2})(\.\d{1,2})?%?$/;
                if (jsx.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多两位正小数"));
                }
              } else {
                if (req.test(value)) {
                  if (Number(value) > 9999999) {
                    return callback(new Error("数值不能大于9999999"));
                  }
                  callback();
                } else {
                  callback(new Error("最多两位正小数"));
                }
              }
            },
            trigger: "change",
          }],
          nonempty: [{
            required: true,
            message: '请选择时间节点',
            trigger: 'change'
          }],
          nonemptys: [{
            required: true,
            message: '请选择奖励规则',
            trigger: 'change'
          }],
          newFieldName: [{
            required: false,
            validator: (rule, value, callback) => {
              let req = /^(100|[1-9]?\d)$/;
              if (req.test(value)) {
                callback();
              } else {
                callback(new Error("请输入0-100的整数"));
              }
            },
            trigger: "change",
          }],
        },
        searchDisplay: false,//搜索条件展开
        searchForm: {
          page: 1,
          count: 10,
          params: {
            supplier_id: '',
            mer_id: '',
            keywords: '',
            cate_ids: '',
            activity_id:''
          }
        },//列表搜索
        formData: {
          tableData: []
        },//商品列表
        loading: false, //刷新
        total: 0,
        multipleSelection: [],//勾选的
        options: [],//供应商列表
        typeData: [],//类目列表
        merchantList: []//搜索条件列表
      };
    },
    watch: {},
    mounted() {
      this.SupplierLists()
      this.getcartlist()
      this.getListWay()
      this.getcatelist()
    },
    methods: {
      //打开设置规则
      settallocation(row, id) {
        this.$refs.refoneallocation.open(row, id)
      },
      getListWay() {
        let param = {
          page: 1,
          count: 100
        }
        getMerchantList(param)
          .then((res) => {
            this.merchantList = res.data.list
          })
          .catch(() => {})
      },
      //切换搜索分类
      handleChange(value) {
        const length = value.length;
        const lastValue = value[length - 1];
        this.searchForm.cate_ids = lastValue;

      },
      //类目列表
      getcartlist() {
        getCateLis().then((res) => {
          this.typeData = res.data;
        });
      },
      //供应商列表
      SupplierLists() {
        supplierLists().then((res) => {
          this.options = res.data;
        });
      },
      closeConfig() {
        this.ifShowProductConfig = false;
        this.getcatelist();
      },
      //移除单个商品
      goodsremoves(id) {
        let arr = []
        arr.push(id)
        let param = {
          id: arr
        }
        goodsremove(param).then((res) => {
            this.loading = true;
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              this.loading = false;
              return;
            }
            this.$messages.success('移除成功');
            this.getcatelist();
          })
          .catch(() => {
            this.loading = false;
          });
      },
      //添加商品弹窗打开
      goodsadd() {
        this.ifShowProductConfig = true
      },
      //批量删除
      batch_deletion() {
        if (!this.multipleSelection.length) {
          return this.$messages.warning('请至少选择一个商品')
        }
        let ids = []
        this.multipleSelection.forEach((item) => {
          ids.push(item.id)
        })
        goodsremove({
            id: ids
          }).then((res) => {
            this.loading = true;
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              this.loading = false;
              return;
            }
            this.$messages.success('移除成功');
            this.getcatelist();
          })
          .catch(() => {
            this.loading = false;
          });
      },
      //单个商品设置规则的回调
      bathsettings(settform){
        this.formData.tableData.forEach((item)=>{
          if(item.id == settform.id){
            item.goods_rule = ''
            item.goods_rule = settform.goods_rule
            // this.$set(item, 'goods_rule', settform.goods_rule)
          }
        })
      },
      //单个商品保存
      singlesubmit(row,id){
        if(Number(row.node_day) < 0){
          this.$messages.warning('发放时间天数不能小于0');
          return
        }else{
          let arr = [];
            arr.push({
              id: id,
              goods_id: row.goods_id,
              node_type: row.node_type,
              node_day: row.node_day,
              award_type: row.award_type,
              level: row.level,
              goods_rule: row.goods_rule
            });
          let param = {
            activity_id: 0,
            goods: arr
          }
          this.loading = true
          goodssave(param).then((res) => {
            if (res.code !== 200 || res.status !== 1) {
              this.loading = false
              return this.$messages.error(res.msg);
            }
            this.loading = false
            this.$messages.success(res.msg);
            this.getcatelist();
          });
        }
      },
      // 提交
      submitForms() {
        this.$refs.allocationform.validate((valid) => {
          if (valid) {
            //判断规则有没有配置的状态
            let statisticsIndexs = true
            this.formData.tableData.find((item, index) => {
              if (!item.goods_rule || item.goods_rule.length == 0) {
                statisticsIndexs = false
              }
            })
            if (statisticsIndexs) {
              let arr = [];
              this.formData.tableData.forEach((item) => {
                arr.push({
                  id: item.id,
                  goods_id: item.goods_id,
                  node_type: item.node_type,
                  node_day: item.node_day,
                  award_type: item.award_type,
                  level: item.level,
                  goods_rule: item.goods_rule
                });
              });
              let param = {
                activity_id: 0,
                goods: arr
              }
              this.settsub = true
              goodssave(param).then((res) => {
                if (res.code !== 200 || res.status !== 1) {
                  this.settsub = false
                  return this.$messages.error(res.msg);
                }
                this.settsub = false
                this.$messages.success(res.msg);
                this.getcatelist();
              });
            } else {
              return this.$messages.warning('请给商品进行规则配置')
            }
          } else {
            this.$messages.error('您有部分配置未完成');
            return false;
          }
        })
      },
      //勾选
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      //选择
      handleSelectionChange(val) {
        this.multipleSelection = val;

      },
      getcatelist() {
        this.loading = true;
        goodslist(this.searchForm)
          .then((res) => {
            this.loading = false;
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              return;
            }
            this.formData.tableData = res.data.list;
            this.total = res.data.total;
          })
          .catch(() => {
            this.loading = false;
          });
      },
      resetting() {
        this.searchForm = {
          supplier: '',
          page: 1,
          count: 10,
          params: {
            supplier_id: '',
            mer_id: '',
            keywords: '',
            cate_ids: '',
            activity_id: ''
          }
        };
        this.getcatelist()
      },
      //页码
      handleSizeChange(val) {},
      handleCurrentChange(val) {},
      //点击搜索
      search() {
        this.$messages({
          type: "success",
          message: "查询成功!",
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .title {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    font-size: 16px;
    line-height: 16px;
  }

  .sn {
    color: #606266;
    font-size: 13px;
  }

  .demo-table-expand {
    display: flex;
    justify-content: start;
    flex-wrap: wrap;
    color: #515a6e;

    div {
      width: 30%;
      height: 40px;
      text-align: center;
      line-height: 40px;
      font-size: 12px;
    }
  }

  .marginTop {
    padding: 0 15px !important;
  }

  .tipbox {
    width: 120px;
    font-size: 12px;
    color: #999;
  }
</style>
